package com.example.demo.entity.thread;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author: zcb
 * @Description:
 * @Date: 2021/10/21
 */
public class Count {
    public static final Object objectLock = new Object();
    public static int count = 0;

    private final Lock lock = new ReentrantLock();

    public void add(int n) {
        lock.lock();
        try {
            count += n;
        } finally {
            lock.unlock();
        }
    }

    public void add2(int n) throws InterruptedException {
        //尝试获取锁
        if (lock.tryLock(1, TimeUnit.SECONDS)) {
            try {
                count += n;
            } finally {
                lock.unlock();
            }
        }
    }
}
